<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\Admin;

use Model\Admin\FieldModel as FieldModel;
use Model\Admin\CategoryModel as CategoryModel;
use Core\Db\Db as Db;
use Expand\Admin\Page as Page;

/**
 * Pes 内容管理模块
 * @author LazyPHP
 * @version 1.0
 */
class Content extends Common {

    private $modelId, $field;

    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
        $db = $this->db('model');
        $data['model_name'] = MODULE;
        $existModel = $db->where('model_name = :model_name')->find($data);
        if ($existModel == false) {
            $this->error('不存在' . MODULE . '模型');
        }
        $this->modelId = $existModel['id'];
        $this->field = FieldModel::fieldList($this->modelId);
    }

    /**
     * 对应模型的数据列表
     */
    public function index() {
        $this->clearUploadRecord();
        $db = $this->db('model');
        $db->tableName(strtolower(MODULE));
        $page = new Page;
        $total = count($db->order('listsort asc, id desc')->select());
        $count = $page->total($total);
        $page->handle();
        $list = $db->order('listsort asc, id desc')->limit("{$page->firstRow}, {$page->listRows}")->select();
        $show = $page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        CategoryModel::$where = 'pm.model_name = "' . MODULE . '"';
        $tree = CategoryModel::getSelectCate();
        $this->assign('tree', $tree);

        $this->display('Content_index');
    }

    /**
     * 初始化数据添加页
     */
    public function add() {
        $this->assign('field', $this->field);
        $actionUrl = $this->url('Admin-'.MODULE.'-insert');
        $this->assign('actionUrl', $actionUrl);
        $this->display('Content_add');
    }

    /**
     * 执行数据添加
     */
    public function insert() {
        foreach ($this->field as $key => $value) {
            //判断提交的字段是否为数组
            if (is_array($_POST[$value['field_name']])) {
                $_POST[$value['field_name']] = implode(',', $_POST[$value['field_name']]);
            }

            //时间转换为时间戳
            if ($value['type'] == 'date') {
                $_POST[$value['field_name']] = strtotime($_POST[$value['field_name']]);
            }

            //判断字段是否为必填和是否过滤HTML标签
            if ($value['required'] == 1) {
                $data[$value['field_name']] = $this->is_p($value['field_name'], empty($value['message']) ? "{$value['name']}为必填项" : $value['message'], $value['htmlentities'] == 0 ? TRUE : FALSE);
            } else {
                $data[$value['field_name']] = $this->p($value['field_name'], $value['htmlentities'] == 0 ? TRUE : FALSE);
            }
        }


        //插入数据
        $db = $this->db(strtolower(MODULE));
        $addResult = $db->add($data);
        $this->determineSqlExecResult($addResult, '添加数据失败!');
        //插入URL
        $url['url'] = $this->setUrl($addResult);
        $addUrl = $db->where("id = {$addResult}")->save($url);
        $this->determineSqlExecResult($addUrl, '为内容添加URL时出错!');
        $this->clearUploadRecord();
        $this->success('添加数据成功!', '/?g=Admin&m=' . MODULE . '&a=index');
    }

    /**
     * 初始化数据编辑
     */
    public function edit() {
        $id = $this->is_g('id', '请选择您要编辑的内容');
        $db = $this->db(strtolower(MODULE));
        $data = $db->where('id = :id')->find(array('id' => $id));
        $this->determineSqlExecResult($data, '不存在此内容');

        foreach ($this->field as $key => $value) {
            foreach ($data as $data_key => $data_value) {
                if ($value['field_name'] == $data_key) {
                    $field[$key] = $value;
                    $field[$key]['value'] = $data_value;
                }
            }
        }

        $this->assign('field', $field);
        $actionUrl = "/?g=Admin&m=" . MODULE . "&a=update&id={$id}";
        $this->assign('actionUrl', $actionUrl);
        $this->display('Content_add');
    }

    /**
     * 更新内容
     */
    public function update() {
        $data['id'] = $this->is_g('id', '请选择您要编辑的内容');
        foreach ($this->field as $key => $value) {
            //判断提交的字段是否为数组
            if (is_array($_POST[$value['field_name']])) {
                $_POST[$value['field_name']] = implode(',', $_POST[$value['field_name']]);
            }

            //时间转换为时间戳
            if ($value['type'] == 'date') {
                $_POST[$value['field_name']] = strtotime($_POST[$value['field_name']]);
            }

            //判断字段是否为必填和是否过滤HTML标签
            if ($value['required'] == 1) {
                $data[$value['field_name']] = $this->is_p($value['field_name'], empty($value['message']) ? "{$value['name']}为必填项" : $value['message'], $value['htmlentities'] == 0 ? TRUE : FALSE);
            } else {
                $data[$value['field_name']] = $this->p($value['field_name'], $value['htmlentities'] == 0 ? TRUE : FALSE);
            }
        }
        $data['url'] = $this->setUrl($data['id']);

        $db = $this->db(strtolower(MODULE));
        $updateResult = $db->where('id = :id')->save($data);
        $this->determineSqlExecResult($updateResult, '更新内容出错');
        $this->clearUploadRecord();
        $this->success('更新内容成功!', '/?g=Admin&m=' . MODULE . '&a=index');
    }

    /**
     * 删除数据
     */
    public function delete() {
        $data['id'] = $this->is_g('id', '请选择您要删除的内容');
        $db = $this->db(strtolower(MODULE));
        $deleteResult = $db->where('id = :id')->delete($data);
        $this->determineSqlExecResult($deleteResult, '删除内容失败');
        $this->success('删除内容成功!', '/?g=Admin&m=' . MODULE . '&a=index');
    }

    /**
     * 搜索内容
     */
    public function search() {
        $this->clearUploadRecord();
        $where = '';
        $data = '';

        if (empty($_POST['clear'])) {
            $data = $_SESSION['page']['data'];
            $where = $_SESSION['page']['where'];
        }

        $catid = $this->p('catid');
        CategoryModel::$where = 'pm.model_name = "' . MODULE . '"';
        if ($catid > 0) {
            $data['catid'] = $catid;
            $where = 'catid = :catid';
            $tree = CategoryModel::getSelectCate($data['catid']);
            $this->assign('tree', $tree);
        } else {
            $tree = CategoryModel::getSelectCate();
            $this->assign('tree', $tree);
        }
        $id = $this->p('id');
        if (!empty($id)) {
            $data['id'] = $id;
            $where .= empty($where) ? 'id = :id' : ' and id = :id';
            $this->assign('id', $id);
        }
        $title = $this->p('title');
        if (!empty($title)) {
            $data['title'] = "%{$title}%";
            $where .= empty($where) ? 'title like :title' : ' and title like :title';
            $this->assign('title', $title);
        }

        $db = $this->db(strtolower(MODULE));
        $page = new Page;
        $total = count($db->where($where)->select($data));
        $count = $page->total($total);
        $page->handle();
        $list = $db->where($where)->order('listsort asc, id desc')->limit("{$page->firstRow}, {$page->listRows}")->select($data);
        $show = $page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        //记录POST提交的数据
        $_SESSION['page']['data'] = $data;
        $_SESSION['page']['where'] = $where;
        $this->display('Content_index');
    }

    /**
     * 进行排序
     */
    public function listsort() {
        $listsort = $this->is_p('listsort', '您没有提交值');

        $db = $this->db(strtolower(MODULE));
        foreach ($listsort as $key => $value) {
            $db->where('id = :id')->save(array('id' => $key, 'listsort' => $value));
        }
        $this->success('排序已更新!', '/?g=Admin&m=' . MODULE . '&a=index');
    }

    /**
     * 设置分类URL
     * @param int $modelId 模型ID
     * @param int $id 内容ID
     * @return string 返回URL
     */
    protected function setUrl($id) {
        $db = $this->db('option');
        $result = $db->where('option_name = "urlModel"')->find();
        $urlModel = json_decode($result['value'], true);
        $url = '';
        if ($urlModel['index'] == '0') {
            $url .= '/index.php/';
        } else {
            $url .= '/';
        }

        switch ($urlModel['urlModel']) {
            case '2':
                $url .= MODULE . "-view-id-{$id}";
                break;
            case '3':
                $url .= MODULE . "/view/id/{$id}";
                break;
            case '1':
            default:
                $url = $urlModel['index'] == '0' ? '/index.php' : '/';
                $url .= "?m=" . MODULE . "&a=view&id={$id}";
        }

        return $url;
    }

}
